﻿using DeviceMaintainGIS.Entity;
using DeviceMaintainGIS.Model;
using DeviceMaintainGIS.Model.Repair;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace DeviceMaintainGIS.BLL.Repair
{

    /// <summary>
    /// 报修操作
    /// </summary>
    public class RepairService
    {
        ///// <summary>
        ///// 根据报修编号查询报修信息
        ///// </summary>
        ///// <param name="RepairId"></param>
        ///// <returns></returns>
        //public ReturnVM<RepairResponse> GetRepairInfoByRepairId(string RepairId)
        //{
        //    ReturnVM<RepairResponse> rm = new ReturnVM<RepairResponse>();
        //    using (CYOADBEntities Entities = new CYOADBEntities())
        //    {
        //        var linq = from a in Entities.Repair_Tab.Where(i => i.RepairId == RepairId)
        //                   join b in Entities.FaultType_Tab on a.FaultType equals b.FaultTypeId
        //                   into tmpFaultType
        //                   let FaultTyp = tmpFaultType.FirstOrDefault()
        //                   //接报人信息
        //                   join d in Entities.tbUser on a.RecipientID equals d.ID
        //                   into tmpRecipient
        //                   let Recipient = tmpRecipient.FirstOrDefault()
        //                   //受理人信息
        //                   join e in Entities.tbUser on a.RMuserID equals e.ID
        //                   into tmpRMuser
        //                   let RMuser = tmpRMuser.FirstOrDefault()
        //                   select new RepairResponse
        //                   {
        //                       RepairId = a.RepairId,
        //                       RepairPersonnel = a.RepairPersonnel,
        //                       RepairTel = a.RepairTel,
        //                       RepairCompany = a.RepairCompany,
        //                       FaultType = a.FaultType,
        //                       FaultName = FaultTyp == null ? "" : FaultTyp.FaultType,
        //                       Describe = a.Describe,
        //                       RecipientID = a.RecipientID,
        //                       RecipientName = Recipient == null ? "" : Recipient.RealName,
        //                       RMuserID = a.RMuserID,
        //                       RMuserName = RMuser == null ? "" : RMuser.RealName,
        //                       RepairTime = a.RepairTime

        //                   };
        //        rm.obj = linq.FirstOrDefault();
        //        rm.Succeed = true;
        //    }
        //    return rm;
        //}
        /// <summary>
        /// 查询报修ID是否存在
        /// </summary>
        /// <param name="RepairId"></param>
        /// <returns></returns>
        public ReturnMessageVM GetRepairInfoByID(string RepairId)
        {
            ReturnMessageVM rm = new ReturnMessageVM();
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                Repair_Tab rt = Entities.Repair_Tab.Where(i => i.RepairId == RepairId).FirstOrDefault();
                //查询报修编号是否存在
                if (rt == null)
                {
                    rm.Succeed = false;
                }
                else
                {
                    rm.Succeed = true;
                }
            }
            return rm;
        }


        /// <summary>
        /// 获取报修信息
        /// </summary>
        /// <returns></returns>
        public ReturnListVM<RepairResponse> GetRepairInfo(RepairSelectRequest Request)
        {
            ReturnListVM<RepairResponse> list = new ReturnListVM<RepairResponse>();
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from k in Entities.RepairRelation_Tab.Where(i => i.State != 2)//0 && i.NextOperatorID == Request.NextOperatorID && i.TableName == "Repair_Tab")
                           join f in Entities.Repair_Tab on k.RelationGuid equals f.Guid
                           into tmpRepair
                           let a = tmpRepair.FirstOrDefault()

                           //join b in Entities.FaultType_Tab on a.FaultType equals b.FaultTypeId
                           //into tmpFaultType
                           //let FaultTyp = tmpFaultType.FirstOrDefault()
                           //接报人信息
                           join d in Entities.tbUser on a.RecipientID equals d.ID
                           into tmpRecipient
                           let Recipient = tmpRecipient.FirstOrDefault()
                           //受理人信息
                           join e in Entities.tbUser on a.RMuserID equals e.ID
                           into tmpRMuser
                           let RMuser = tmpRMuser.FirstOrDefault()
                           select new RepairResponse
                           {
                               RepairId = a.RepairId,
                               RepairPersonnel = a.RepairPersonnel,
                               RepairTel = a.RepairTel,
                               RepairCompany = a.RepairCompany,
                               FaultType = a.FaultType,
                               //FaultName = FaultTyp == null ? "" : FaultTyp.FaultType,
                               Describe = a.Describe,
                               RecipientID = a.RecipientID,
                               RecipientName = Recipient == null ? "" : Recipient.RealName,
                               RMuserID = a.RMuserID,
                               RMuserName = RMuser == null ? "" : RMuser.RealName,
                               RepairTime = a.RepairTime,
                               Step = k.Step
                           };
                //报修编号查询条件
                if (!string.IsNullOrEmpty(Request.RepairId))
                {

                    linq = linq.Where(i => i.RepairId.Contains(Request.RepairId));
                    //linq = linq.Where(i => i.RepairId == Request.RepairId);
                }

                list.TotalCount = linq.Count();
                List<RepairResponse> RepairResponseList = linq.OrderByDescending(i => i.RepairTime).Take(Request.PagesSize * Request.PageIndex).Skip(Request.PagesSize * (Request.PageIndex - 1)).ToList();
                list.List = RepairResponseList;
                list.PageIndex = Request.PageIndex;
                list.PagesSize = Request.PagesSize;
            }
            return list;
        }

        /// <summary>
        /// 报修结束流程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnMessageVM RepairEnd(RepairEndRequest request)
        {
            ReturnMessageVM rm = new ReturnMessageVM();
            rm.Succeed = true;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    //报修结束表
                    RepairEnd_Tab ret = new RepairEnd_Tab();
                    ret.Guid = Guid.NewGuid().ToString();
                    ret.RepairId = request.RepairId;
                    ret.EndTime = System.DateTime.Now;
                    Entities.RepairEnd_Tab.Add(ret);
                    Entities.Entry<RepairEnd_Tab>(ret).State = System.Data.Entity.EntityState.Added;

                    //上一级保修关系更改
                    RepairRelation_Tab stepRepairRelation = Entities.RepairRelation_Tab.Where(i => i.RepairId == request.RepairId && i.Step == (request.Step - 1) && i.State == 0).FirstOrDefault();
                    if (stepRepairRelation != null)
                    {
                        stepRepairRelation.State = 1;
                        Entities.RepairRelation_Tab.Add(stepRepairRelation);
                        Entities.Entry<RepairRelation_Tab>(stepRepairRelation).State = System.Data.Entity.EntityState.Modified;
                    }


                    //报修关系表
                    RepairRelation_Tab rrt = new RepairRelation_Tab();

                    rrt.RepairId = request.RepairId;
                    rrt.AddTime = System.DateTime.Now;
                    rrt.TableName = "RepairEnd_Tab";
                    rrt.RelationGuid = ret.Guid;
                    rrt.Step = request.Step;
                    rrt.OperatorID = request.OperatorID;
                    rrt.NextOperatorID = -1;

                    rrt.State = 1;
                    rrt.Operator = -1;


                    Entities.RepairRelation_Tab.Add(rrt);
                    Entities.Entry<RepairRelation_Tab>(rrt).State = System.Data.Entity.EntityState.Added;

                    Entities.SaveChanges();
                    //提交事务
                    transaction.Complete();
                }
            }
            return rm;
        }
        /// <summary>
        /// 添加报修
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ReturnMessageVM RepairAdd(RepairRequest request)
        {
            string newID = Guid.NewGuid().ToString();
            ReturnMessageVM rm = new ReturnMessageVM();
            rm.Succeed = true;
            Repair_Tab rt = new Repair_Tab();
            rt.Guid = newID;


            rt.RepairPersonnel = request.RepairPersonnel;
            rt.RepairTel = request.RepairTel;
            rt.RepairCompany = request.RepairCompany;
            rt.FaultType = request.FaultType;
            rt.Describe = request.Describe;
            rt.RecipientID = request.Recipient;
            rt.RMuserID = request.RMuserID;
            rt.RepairTime = System.DateTime.Now;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {


                        //string RepairId = Entities.Repair_Tab.Where(i => i.RepairId.Contains(request.RepairId)).Max(i => i.RepairId);


                        ////if (tmp != null)
                        ////{
                        ////    rm.Succeed = false;
                        ////    rm.Message = "报修编号已存在！";
                        ////    return rm;

                        ////}
                        //if (string.IsNullOrEmpty( RepairId))
                        //{
                        //    RepairId = request.RepairId + "-0001";
                        //}
                        //else
                        //{
                        //    int tmp = Int32.Parse(RepairId.Substring(RepairId.Length - 4)); ;
                        //    tmp += 1;
                        //    RepairId = request.RepairId +"-"+ tmp.ToString().PadLeft(4, '0');
                        //}
                        int tmp = Entities.Repair_Tab.Where(i => i.RepairId == request.RepairId).Count();
                        if (tmp > 0)
                        {
                            rm.Succeed = false;
                            rm.Message = "保修编号已存在！请从新输入！";
                        }
                        string RepairId = request.RepairId;
                        rt.RepairId = RepairId;

                        Entities.Repair_Tab.Add(rt);
                        Entities.Entry<Repair_Tab>(rt).State = System.Data.Entity.EntityState.Added;

                        //关系表信息
                        RepairRelation_Tab rrt = new RepairRelation_Tab();

                        rrt.RepairId = RepairId;
                        rrt.AddTime = System.DateTime.Now;
                        rrt.TableName = "Repair_Tab";
                        rrt.RelationGuid = newID;
                        rrt.Step = 1;
                        rrt.OperatorID = request.Recipient;
                        rrt.NextOperatorID = request.RMuserID;
                        rrt.Operator = 2;
                        rrt.State = 0;
                        Entities.RepairRelation_Tab.Add(rrt);
                        Entities.Entry<RepairRelation_Tab>(rrt).State = System.Data.Entity.EntityState.Added;


                        Entities.SaveChanges();
                        //提交事务
                        transaction.Complete();

                    }
                    catch (Exception ex)
                    {
                        rm.Succeed = false;
                        rm.Message = "入库失败";
                    }
                }

            }
            return rm;
        }

        /// <summary>
        /// 获取新的RepairId
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string GetNewRepairId(string request)
        {
            string RepairId = "";
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                string tmpId = request.Substring(0, 4);


                int intRepairId = Entities.Repair_Tab.Where(i => i.RepairId.Contains(tmpId)).Count();

                if (intRepairId < 1)
                {
                    RepairId = request + "-0001";
                }
                else
                {
                    RepairId = Entities.Repair_Tab.Where(i => i.RepairId.Contains(RepairId)).OrderByDescending(i => i.RepairTime).FirstOrDefault().RepairId;
                    int tmp = Int32.Parse(RepairId.Substring(RepairId.Length - 4)); ;
                    tmp += 1;
                    RepairId = request + "-" + tmp.ToString().PadLeft(4, '0');
                }
                //if (tmp != null)
                //{
                //    rm.Succeed = false;
                //    rm.Message = "报修编号已存在！";
                //    return rm;

                //}
                //if (string.IsNullOrEmpty(RepairId))
                //{
                //    RepairId = request + "-0001";
                //}
                //else
                //{
                //    int tmp = Int32.Parse(RepairId.Substring(RepairId.Length - 4)); ;
                //    tmp += 1;
                //    RepairId = request + "-" + tmp.ToString().PadLeft(4, '0');
                //}
            }
            return RepairId;
        }

        /// <summary>
        /// 获取报修信息
        /// </summary>
        /// <returns></returns>
        public ReturnListVM<AfterSaleRecordResponse> GetAfterSaleRecord(AfterSaleRecordRequest Request)
        {
            ReturnListVM<AfterSaleRecordResponse> list = new ReturnListVM<AfterSaleRecordResponse>();
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = Entities.RepairRelation_Tab.Where(i => i.State != 2).GroupBy(a => a.RepairId).Select(i => (new { RepairId = i.Key, Step = i.Max(item => item.Step) }));
                var LinqAfterSaleRecord = from a in linq
                                          join f in Entities.Repair_Tab on a.RepairId equals f.RepairId
                                          into tmpRepair
                                          let RepaiTab = tmpRepair.FirstOrDefault()
                                          //获取状态
                                          join b in Entities.RepairRelation_Tab on new { A = a.RepairId, B = a.Step } equals new { A = b.RepairId, B = b.Step }
                                          into tmpRepairRelation
                                          let RepairRelation = tmpRepairRelation.FirstOrDefault()

                                          //受理人信息
                                          join e in Entities.tbUser on RepaiTab.RMuserID equals e.ID
                                          into tmpRMuser
                                          let RMuser = tmpRMuser.FirstOrDefault()

                                          //保修类型
                                          join b in Entities.FaultType_Tab on RepaiTab.FaultType equals b.FaultTypeId
                                          into tmpFaultType
                                          let FaultTyp = tmpFaultType.FirstOrDefault()
                                          select new AfterSaleRecordResponse
                                          {
                                              RepairId = a.RepairId,
                                              State = RepairRelation.State,
                                              FaultName = FaultTyp.FaultType,
                                              FaultType = RepaiTab.FaultType,
                                              RMuserID = RepaiTab.RMuserID,
                                              RMuserName = RMuser.RealName,
                                              RepairCompany = RepaiTab.RepairCompany,
                                              RepairPersonnel = RepaiTab.RepairPersonnel,
                                              RepairTel = RepaiTab.RepairTel,
                                              RepairTime = RepaiTab.RepairTime,
                                              Step = a.Step,
                                              Operator = RepairRelation.Operator
                                          };
                DateTime tmp = DateTime.ParseExact("19000101", "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                //报修编号查询条件
                if (!string.IsNullOrEmpty(Request.RepairId))
                {

                    LinqAfterSaleRecord = LinqAfterSaleRecord.Where(i => i.RepairId.Contains(Request.RepairId));
                    //LinqAfterSaleRecord = LinqAfterSaleRecord.Where(i => i.RepairId == Request.RepairId);
                }
                //报修单位查询条件
                if (!string.IsNullOrEmpty(Request.RepairCompany))
                {
                    LinqAfterSaleRecord = LinqAfterSaleRecord.Where(i => i.RepairCompany == Request.RepairCompany);
                }
                //时间查询
                if (Request.StartRepairTime != tmp && Request.EndRepairTime != tmp)
                {
                    LinqAfterSaleRecord = LinqAfterSaleRecord.Where(a => a.RepairTime >= Request.StartRepairTime && a.RepairTime <= Request.EndRepairTime);
                }
                //步骤查询
                if (Request.Operator != -1)
                {
                    LinqAfterSaleRecord = LinqAfterSaleRecord.Where(a => a.Operator == Request.Operator);
                }
                list.TotalCount = LinqAfterSaleRecord.Count();
                List<AfterSaleRecordResponse> RepairResponseList = LinqAfterSaleRecord.OrderByDescending(i => i.RepairTime).Take(Request.PagesSize * Request.PageIndex).Skip(Request.PagesSize * (Request.PageIndex - 1)).ToList();
                list.List = RepairResponseList;
                list.PageIndex = Request.PageIndex;
                list.PagesSize = Request.PagesSize;

            }
            return list;
        }

        /// <summary>
        /// 根据报修编号查询报修关系详情
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public ReturnListVM<RepairRelation> GetRepairRelationInfo(RepairSelectRequest Request)
        {
            ReturnListVM<RepairRelation> list = new ReturnListVM<RepairRelation>();
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var Linq = from a in Entities.RepairRelation_Tab
                           select new RepairRelation
                           {
                               RepairId = a.RepairId,
                               AddTime = a.AddTime,
                               NextOperatorID = a.NextOperatorID,
                               Operator = a.Operator,
                               OperatorID = a.OperatorID,
                               RelationGuid = a.RelationGuid,
                               State = a.State,
                               Step = a.Step,
                               TableName = a.TableName,
                           };
                if (!string.IsNullOrEmpty(Request.RepairId))
                {
                    Linq = Linq.Where(i => i.RepairId == Request.RepairId);
                }
                list.TotalCount = Linq.Count();
                List<RepairRelation> RepairRelationList = Linq.OrderByDescending(i => i.Step).Take(Request.PagesSize * Request.PageIndex).Skip(Request.PagesSize * (Request.PageIndex - 1)).ToList();
                list.List = RepairRelationList;
                list.PageIndex = Request.PageIndex;
                list.PagesSize = Request.PagesSize;
            }
            return list;
        }
    }
}
